import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordNameGeneric, RouteRecordRaw } from "vue-router";

import page404 from "@/views/404.vue";
import { loaderRouter, useUserStore } from "@/pinna/userinfo";
import { getUserInfo, getUserMenu } from "@/api/rbacApi";
import { useSysStore } from "@/pinna/sys";
const modules = import.meta.glob("@/views/**/*.vue");

let indexPage = [] as any[];
// 2. 配置路由
const routes: RouteRecordRaw[] = [
  {
    name: "index",
    path: "/index",
    component: () => import("@/views/index.vue"),
    children: indexPage,
  },
  {
    name: "login",
    path: "/login",
    component: () => import("@/views/login.vue"),
  },
  {
    name: "404",
    path: "/:pathMatch(.*)*",
    component: page404,
  },
];
// 1.返回一个 router 实列，为函数，里面有配置项（对象） history
const router = createRouter({
  history: createWebHistory(),
  routes,
});

function flushSysInfo(to: any) {
  if (to) {
    let sysStore = useSysStore();
    //默认开启的路由
    sysStore.setDefaultOpenMenu(to.meta.parentResourceCode);
    //默认的面包屑
    let menuTree = useUserStore().getPermissionMenuTree;
    let itemArray = []
    let tmpItem = menuTree
    for (const resourceCode of to.meta.parentResourceCode) {
      let findItem = tmpItem.find((item :any)=>item.resourceCode = resourceCode)
      if(findItem){
        tmpItem = findItem.sonList
        itemArray.push(findItem)
      }else{
        break
      }
    }
    sysStore.setBreadCrumb(itemArray);
  }
}

router.beforeEach((to, from, next) => {
  //资源刷新，设置系统预设值
  if (to.path.startsWith("/index")) {
    const userStore = useUserStore();

    //unload user resource
    if (!userStore.getIsRoutesLoaded) {
      console.log("user and resource loading");

      //loading user
      getUserInfo().then((userInfo) => {
        //loading resource
        getUserMenu().then((resource) => {
          userStore.setUser(userInfo);
          userStore.setPermission(resource);

          //路由加载
          let routePage = loaderRouter() as any[];
          addPage(routePage);

          flushSysInfo(to)
          next();
        });
      });
    } else {
      flushSysInfo(to)
      next();
    }
  } else {
    next();
  }
});

// 3导出路由   然后去 main.ts 注册 router.ts
export default router;

//路由信息懒加载
export async function initIndex() {
  console.log("sys userinfo init");
  const userStore = useUserStore();
  //loading user
  let resource = await getUserMenu();
  let loginUserInfo = await getUserInfo();

  userStore.setUser(loginUserInfo);
  userStore.setPermission(resource);
  //路由加载
  let routePage = loaderRouter() as any[];
  addPage(routePage);
}

/**
 * 添加路由
 * @param routerPage
 */
export function addPage(routerPage: any[]) {
  console.log("loading system router");

  for (const item of routerPage) {
    router.addRoute("index", item);
  }
}

// 使用
export function loadComponent(pagePath: string) {
  const path = `/src/views${pagePath}.vue`;

  let component = modules[path];
  if (component) {
    return component;
  }

  return Promise.reject(new Error(`页面不存在: ${path}`));
}
